<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vuex详解 | Kylin</title><meta name="keywords" content="Vue,Vuex"><meta name="author" content="Kylin"><meta name="copyright" content="Kylin"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Vuex是做什么的？官方解释：Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。  它采用 集中式存储管理 应用的所有组件的状态，并以相应的规则保证状态以一种可预测的方式发生变化。 Vuex 也集成到 Vue 的官方调试工具 devtools extension，提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。  状态管理到底是什么？  状态管理模式">
<meta property="og:type" content="article">
<meta property="og:title" content="Vuex详解">
<meta property="og:url" content="https://www.codekylin.cn/6620.html">
<meta property="og:site_name" content="Kylin">
<meta property="og:description" content="Vuex是做什么的？官方解释：Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。  它采用 集中式存储管理 应用的所有组件的状态，并以相应的规则保证状态以一种可预测的方式发生变化。 Vuex 也集成到 Vue 的官方调试工具 devtools extension，提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。  状态管理到底是什么？  状态管理模式">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.codekylin.cn/github/img/img/博客封面7.jpg">
<meta property="article:published_time" content="2020-07-02T08:07:54.000Z">
<meta property="article:modified_time" content="2022-07-12T11:42:49.984Z">
<meta property="article:author" content="Kylin">
<meta property="article:tag" content="Vue">
<meta property="article:tag" content="Vuex">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.codekylin.cn/github/img/img/博客封面7.jpg"><link rel="shortcut icon" href="https://qiniu.codekylin.cn/img/20200807181548.png"><link rel="canonical" href="https://www.codekylin.cn/6620"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><meta name="google-site-verification" content="gzeyWstt6NoTZKh7YFYNLNziL8HIZ8YH2Ug7xTDX5-Y"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f76c34daefe747deee7c7be3ead2ba80";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-159334016-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-159334016-1');
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":90,"position":"top","messagePrev":"自上次更新以来已经","messageNext":"天，文章的内容可能已过时或存在差异。"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50000,"languages":{"author":"作者: Kylin","link":"链接: ","source":"来源: Kylin","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#FF0000","bgDark":"#2d3035","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-12 19:42:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/custom.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_1993646_z05rabxf05h.css"><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/icon.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Kylin" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="onerror=null;src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://qiniu.codekylin.cn/github/img/img/博客封面7.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Kylin</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vuex详解</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-07-02T08:07:54.000Z" title="发表于 2020-07-02 16:07:54">2020-07-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-12T11:42:49.984Z" title="更新于 2022-07-12 19:42:49">2022-07-12</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Vue/">Vue</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Vue/Vuex/">Vuex</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="Vuex是做什么的？"><a href="#Vuex是做什么的？" class="headerlink" title="Vuex是做什么的？"></a>Vuex是做什么的？</h2><p>官方解释：Vuex 是一个专为 Vue.js 应用程序开发的<strong>状态管理模式</strong>。</p>
<ul>
<li>它采用 集中式存储管理 应用的所有组件的状态，并以相应的规则保证状态以一种可预测的方式发生变化。</li>
<li>Vuex 也集成到 Vue 的官方调试工具 <a target="_blank" rel="noopener" href="https://github.com/vuejs/vue-devtools">devtools</a><a target="_blank" rel="noopener" href="https://github.com/vuejs/vue-devtools"> extension</a>，提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。</li>
</ul>
<p><strong>状态管理</strong>到底是什么？</p>
<ul>
<li><strong>状态管理模式、集中式存储管理</strong>这些名词听起来就非常高大上，让人捉摸不透。</li>
<li>其实，你可以简单的将其看成把需要多个组件共享的变量全部存储在一个对象里面。</li>
<li>然后，将这个对象放在顶层的Vue实例中，让其他组件可以使用</li>
<li>那么，多个组件是不是就可以共享这个对象中的所有变量属性了呢？</li>
</ul>
<p>等等，如果是这样的话，为什么官方还要专门出一个插件Vuex呢？难道我们不能自己封装一个对象来管理吗？</p>
<ul>
<li>当然可以，只是我们要先想想VueJS带给我们最大的便利是什么呢？没错，就是<strong>响应式</strong>。</li>
<li>如果你自己封装实现一个对象能不能保证它里面所有的属性做到响应式呢？当然也可以，只是自己封装可能稍微麻烦一些。</li>
<li>不用怀疑，Vuex就是为了提供这样一个在多个组件间共享状态的插件，用它就可以了。</li>
</ul>
<h2 id="管理什么状态呢？"><a href="#管理什么状态呢？" class="headerlink" title="管理什么状态呢？"></a>管理什么状态呢？</h2><p>但是，有什么状态时需要我们在多个组件间共享的呢？</p>
<ul>
<li>如果你做过大型开放，你一定遇到过多个状态，在多个界面间的共享问题。</li>
<li>比如用户的登录状态、用户名称、头像、地理位置信息等等。</li>
<li>比如商品的收藏、购物车中的物品等等。</li>
<li>p这些状态信息，我们都可以放在统一的地方，对它进行保存和管理，而且它们还是响应式的（待会儿我们就可以看到代码了，莫着急）。</li>
</ul>
<h2 id="单界面的状态管理"><a href="#单界面的状态管理" class="headerlink" title="单界面的状态管理"></a>单界面的状态管理</h2><p>我们知道，要在单个组件中进行状态管理是一件非常简单的事情</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702162701.png" alt="image-20200702162659391"></p>
<p>这图片中的三种东西，怎么理解呢？</p>
<ul>
<li>State：不用多说，就是我们的状态。（你姑且可以当做就是data中的属性）</li>
<li>View：视图层，可以针对State的变化，显示不同的信息。（这个好理解吧？）</li>
<li>Actions：这里的Actions主要是用户的各种操作：点击、输入等等，会导致状态的改变。</li>
</ul>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702163323.png" alt="image-20200702163322182"></p>
<h2 id="多界面状态管理"><a href="#多界面状态管理" class="headerlink" title="多界面状态管理"></a><strong>多界面状态管理</strong></h2><p>Vue已经帮我们做好了单个界面的状态管理，但是如果是多个界面呢？</p>
<ul>
<li>多个试图都依赖同一个状态（一个状态改了，多个界面需要进行更新）</li>
<li>不同界面的Actions都想修改同一个状态（Home.vue需要修改，Profile.vue也需要修改这个状态）</li>
</ul>
<p>也就是说对于某些状态(状态1/状态2/状态3)来说只属于我们某一个试图，但是也有一些状态(状态a/状态b/状态c)属于多个试图共同想要维护的</p>
<ul>
<li>状态1/状态2/状态3你放在自己的房间中，你自己管理自己用，没问题。</li>
<li>但是状态a/状态b/状态c我们希望交给一个大管家来统一帮助我们管理！！！</li>
<li>没错，Vuex就是为我们提供这个大管家的工具。</li>
</ul>
<p>全局单例模式（大管家）</p>
<ul>
<li>我们现在要做的就是将共享的状态抽取出来，交给我们的大管家，统一进行管理。</li>
<li>之后，你们每个视图，按照我<strong>规定好的</strong>规定，进行访问和修改等操作。</li>
<li>这就是Vuex背后的基本思想</li>
</ul>
<h2 id="Vuex的基本使用"><a href="#Vuex的基本使用" class="headerlink" title="Vuex的基本使用"></a>Vuex的基本使用</h2><p>首先通过<code>npm install vuex --save</code>下载安装Vuex。接着创建目录<code>store</code>,再目录下编写index.js</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702165312.png" alt="code-snapshot (61)"></p>
<p>接着再main.js中引入store对象。这样，在其他Vue组件中，我们就可以通过<code>this.$store</code>的方式，获取到这个store对象了</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702165355.png" alt="code-snapshot (62)"></p>
<p>如何获取使用其中的值呢？例如state对象中的counter值。只需要通过<code>$store.state.counter</code>即可获取到相应的属性值。</p>
<p>HelloVuex.vue文件中</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702165600.png" alt="image-20200702165558747"></p>
<p>App.vue文件中注册组件对象，并也获取到state对象中的counter值，并通过按钮对其值进行加减</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702165700.png" alt="image-20200702165658620"></p>
<p>查看效果，可以发现这值是公共的每个组件都能对其操作并获得其对应属性的值。</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702165918.gif" alt="GIF1658"></p>
<p><strong>不过直接通过<code>$store.state.counter</code>对其进行加减是不符合规范的。这里只做效果演示</strong></p>
<h2 id="Vuex状态管理图例"><a href="#Vuex状态管理图例" class="headerlink" title="Vuex状态管理图例"></a><strong>Vuex状态管理图例</strong></h2><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702170551.png" alt="image-20200702170550064"></p>
<p><mark><strong>通过官方图例，我们发现如果我们要修改<code>State</code>就要通过<code>Mutations</code>来对其进行操作，才能被官方的开发工具进行检测。否则我们如上文一样直接修改<code>State</code>的属性值，是不能被Devtools检测到我们进行的操作，不利于我们的调试！<code>Actios</code>是用来进行异步操作的，发送网络请求</strong></mark></p>
<p>我们对上文中的效果展示进行修改，通过<code>Mutations</code>来对<code>State</code>进行操作</p>
<p>首先修改store文件中的index.js文件，再<code>mutatios</code>创建两个方法，方法参数值为<code>state</code>对象</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702171620.png" alt="image-20200702171618481"></p>
<p>接着修改App.vue</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702171738.png" alt="image-20200702171736653"></p>
<p>同样绑定两个方法，方法中通过<code>this.$store.commit()</code>传入的字符串值对应着<code>mutatios</code>的方法名。</p>
<p>查看页面效果，能正常对其操作，并能被开发工具检测记录</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702172042.gif" alt="GIF1720"></p>
<h2 id="State"><a href="#State" class="headerlink" title="State"></a>State</h2><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112936.png" alt="image-20200703112935165"></p>
<p>Vuex 使用 state 来存储应用中需要共享的状态。通过<code>$store.state</code>可以获得state中的状态值。</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702202200.png" alt="image-20200702202159244"></p>
<h2 id="Getters"><a href="#Getters" class="headerlink" title="Getters"></a>Getters</h2><p>Vuex 允许我们在 store 中定义“getter”（可以认为是 <mark>store 的计算属性</mark>）。就像计算属性一样，getter 的返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算。</p>
<p>Getter 接受 <code>state</code> 作为其第一个参数</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702203659.png" alt="image-20200702203658492"></p>
<p>Getter 会暴露为 <code>store.getters</code> 对象，你可以以属性的形式访问这些值</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702203731.png" alt="image-20200702203730221"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702203748.png" alt="image-20200702203747102"></p>
<p>查看页面效果</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200702204019.gif" alt="GIF2039"></p>
<p>在<code>state</code>添加新的数组属性students。属性值为学生信息</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703091657.png" alt="image-20200703091655295"></p>
<p>如果要显示年龄大于20的学生信息，可以使用Js的<code>filter</code>方法</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703091826.png" alt="image-20200703091824810"></p>
<p>Getter 也可以接受其他 <code>getter</code> 作为第二个参数</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703092047.png" alt="image-20200703092044301"></p>
<p>getters默认是不能传递参数的, 如果希望传递参数, 你可以通过让 getter <strong>返回一个函数</strong>，来实现给 getter 传参。</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703092259.png" alt="image-20200703092258132"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703092352.png" alt="image-20200703092351027"></p>
<p>查看页面效果</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703092613.png" alt="image-20200703092611560"></p>
<h2 id="mutations"><a href="#mutations" class="headerlink" title="mutations"></a>mutations</h2><p>Vuex的store状态的更新唯一方式：<mark><strong>提交Mutation</strong></mark></p>
<p>Vuex 中的 mutation 非常类似于事件：每个 mutation 都有一个字符串的 <strong>事件类型 (type)</strong> 和 一个 <strong>回调函数 (handler)</strong>。这个回调函数就是我们实际进行状态更改的地方，并且它会接受 <code>state</code>作为第一个参数</p>
<h3 id="状态更新"><a href="#状态更新" class="headerlink" title="状态更新"></a><strong>状态更新</strong></h3><p>mutation的定义方式</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703095218.png" alt="image-20200703095206364"></p>
<p>通过mutation更新</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703095230.png" alt="image-20200703095229274"></p>
<h3 id="提交载荷"><a href="#提交载荷" class="headerlink" title="提交载荷"></a>提交载荷</h3><p>你可以向 <code>store.commit</code> 传入额外的参数，即 mutation 的 <strong>载荷（payload）</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703100044.png" alt="image-20200703100042990"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703100148.png" alt="image-20200703100147604"></p>
<p>在大多数情况下，载荷应该是一个对象，这样可以包含多个字段并且记录的 mutation 会更易读</p>
<p>添加mutations</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703100506.png" alt="image-20200703100504810"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703100613.png" alt="image-20200703100612397"></p>
<p>查看页面效果</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703100723.gif" alt="GIF1006"></p>
<h3 id="对象风格的提交方式"><a href="#对象风格的提交方式" class="headerlink" title="对象风格的提交方式"></a>对象风格的提交方式</h3><p><mark><strong>当使用对象风格的提交方式，整个对象都作为载荷传给 mutation 函数</strong></mark></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703101815.png" alt="image-20200703101814186"></p>
<p>此时就不能直接获取count，而是通过对象属性获取count</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703101915.png" alt="image-20200703101912745"></p>
<h3 id="Mutation-需遵守-Vue-的响应规则"><a href="#Mutation-需遵守-Vue-的响应规则" class="headerlink" title="Mutation 需遵守 Vue 的响应规则"></a>Mutation 需遵守 Vue 的响应规则</h3><p>既然 Vuex 的 store 中的状态是响应式的，那么当我们变更状态时，监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项：</p>
<ol>
<li>最好提前在你的 store 中初始化好所有所需属性。</li>
<li>当需要在对象上添加新属性时，你应该</li>
</ol>
<ul>
<li>使用 <code>Vue.set(obj, &#39;newProp&#39;, 123)</code>, 或者</li>
<li>以新对象替换老对象。例如，利用<a target="_blank" rel="noopener" href="https://github.com/tc39/proposal-object-rest-spread">对象展开运算符</a>我们可以这样写：</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">state.obj = &#123; ...state.obj, <span class="attr">newProp</span>: <span class="number">123</span> &#125;</span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703102133.png" alt="image-20200703102131651"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703102139.png" alt="image-20200703102138779"></p>
<p>查看下面代码的方式一和方式二。都可以让state中的属性是响应式的.</p>
<h3 id="使用常量替代-Mutation-事件类型"><a href="#使用常量替代-Mutation-事件类型" class="headerlink" title="使用常量替代 Mutation 事件类型"></a>使用常量替代 Mutation 事件类型</h3><p>我们来考虑下面的问题</p>
<ul>
<li>在mutation中, 我们定义了很多事件类型(也就是其中的方法名称).</li>
<li>当我们的项目增大时, Vuex管理的状态越来越多, 需要更新状态的情况越来越多, 那么意味着Mutation中的方法越来越多.</li>
<li>方法过多, 使用者需要花费大量的经历去记住这些方法, 甚至是多个文件间来回切换, 查看方法名称, 甚至如果不是复制的时候, 可能还会出现写错的情况.</li>
</ul>
<p>如何避免上述的问题呢?</p>
<ul>
<li>在各种Flux实现中, 一种很常见的方案就是使用<strong>常量</strong>替代Mutation<strong>事件的类型**</strong>.**</li>
<li>我们可以将这些常量放在一个单独的文件中, 方便管理以及让整个app所有的事件类型一目了然.</li>
</ul>
<p>创建一个mutation-types.js, 并且在其中定义我们的常量</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703104537.png" alt="image-20200703104535762"></p>
<p>在store中的index.js引入，修改代码，通过<code>[常量名]</code>定义事件类型type</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703104758.png" alt="image-20200703104756813"></p>
<p>同样在App.vue引入，修改代码</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703105103.png" alt="image-20200703105101302"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703105157.gif" alt="GIF1051"></p>
<h3 id="Mutation-必须是同步函数"><a href="#Mutation-必须是同步函数" class="headerlink" title="Mutation 必须是同步函数"></a>Mutation 必须是同步函数</h3><p>通常情况下, Vuex要求我们Mutation中的方法必须是同步方法.</p>
<ul>
<li>主要的原因是当我们使用devtools时, 可以devtools可以帮助我们捕捉mutation的快照.</li>
<li>但是如果是异步操作, 那么devtools将不能很好的追踪这个操作什么时候会被完成</li>
</ul>
<p>比如我们之前的代码, 当执行更新时, devtools中会有如下信息: 图1</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703105317.png" alt="image-20200703105314860"></p>
<p>但是, 如果Vuex中的代码, 我们使用了异步函数</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703105428.png" alt="image-20200703105421949"></p>
<h2 id="Actions"><a href="#Actions" class="headerlink" title="Actions"></a>Actions</h2><p>我们强调, 不要再Mutation中进行异步操作</p>
<p>但是某些情况, 我们确实希望在Vuex中进行一些异步操作, 比如网络请求, 必然是异步的. 这个时候怎么处理呢?</p>
<p><mark><strong>Action类似于Mutation, 但是是用来代替Mutation进行异步操作的.</strong></mark></p>
<p>让我们来注册一个简单的 action</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112052.png" alt="image-20200703112051380"></p>
<p>在Vue组件中, 如果我们调用action中的方法, 那么就需要使用<code>dispatch</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112224.png" alt="image-20200703112223177"></p>
<p>查看效果</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112259.gif" alt="GIF1122"></p>
<p>同样的, 也是支持传递payload，同mutatios一样</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112518.png" alt="image-20200703112517594"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112536.png" alt="image-20200703112534995"></p>
<p>查看效果</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112620.gif" alt="GIF1125"></p>
<p>context是什么?</p>
<ul>
<li><p>context是和store对象具有相同方法和属性的对象.</p>
</li>
<li><p>也就是说, 我们可以通过context去进行commit相关的操作, 也可以获取context.state等.</p>
</li>
<li><p>但是注意, 这里它们并不是同一个对象, 为什么呢? 我们后面学习Modules的时候, 再具体说.</p>
</li>
</ul>
<p>这样的代码是否多此一举呢?</p>
<ul>
<li>我们定义了actions, 然后又在actions中去进行commit, 这不是脱裤放屁吗?</li>
<li>事实上并不是这样, 如果在Vuex中有异步操作, 那么我们就可以在actions中完成了.</li>
</ul>
<p>前面我们学习ES6语法的时候说过, Promise经常用于异步操作</p>
<p>在Action中, 我们可以将异步操作放在一个Promise中, 并且在成功或者失败后, 调用对应的resolve或reject.</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112756.png" alt="image-20200703112754549"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703112811.png" alt="image-20200703112809900"></p>
<h2 id="Module"><a href="#Module" class="headerlink" title="Module"></a><strong>Module</strong></h2><p>Module是模块的意思, 为什么在Vuex中我们要使用模块呢?</p>
<p>Vue使用单一状态树,那么也意味着很多状态都会交给Vuex来管理.</p>
<p>当应用变得非常复杂时,store对象就有可能变得相当臃肿.</p>
<p>为了解决这个问题, Vuex允许我们将store分割成模块(Module), 而每个模块拥有自己的state、mutations、actions、getters等</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703113119.png" alt="image-20200703113117709"></p>
<h3 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h3><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703114217.png" alt="image-20200703114215642"></p>
<p>App.vue中，由于会把模块放到store中的state作为一个对象属性，所以要通过<code>$store.state</code>才能访问到</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703114308.png" alt="image-20200703114306964"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703114414.png" alt="image-20200703114412618"></p>
<h3 id="Module局部状态"><a href="#Module局部状态" class="headerlink" title="Module局部状态"></a>Module局部状态</h3><p>我们在moduleA中添加state、mutations、getters</p>
<p><strong>mutation和getters接收的第一个参数是局部状态对象</strong></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703114717.png" alt="image-20200703114715568"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703114723.png" alt="image-20200703114722551"></p>
<p><mark><strong>注意:虽然, 我们的doubleCount和increment都是定义在对象内部的.但是在调用的时候, 依然是通过this.$store来直接调用的.且不能与外部的store中定义的重名否则不知道调用哪个，调用顺序是先去store中找，在从各个模块中查找调用！</strong></mark></p>
<h3 id="Actions的写法"><a href="#Actions的写法" class="headerlink" title="Actions的写法"></a>Actions的写法</h3><p>actions的写法呢? 接收一个context参数对象,使用对象的结构获取相应参数</p>
<p>局部状态通过 context.state 暴露出来，根节点状态则为 context.rootState</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703115051.png" alt="image-20200703115049766"></p>
<p>如果getters中也需要使用全局的状态, 可以接受更多的参数</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703115103.png" alt="image-20200703115102040"></p>
<h2 id="项目结构"><a href="#项目结构" class="headerlink" title="项目结构"></a>项目结构</h2><p>Vuex 并不限制你的代码结构。但是，它规定了一些需要遵守的规则：</p>
<ol>
<li>应用层级的状态应该集中到单个 store 对象中。</li>
<li>提交 <strong>mutation</strong> 是更改状态的唯一方法，并且这个过程是同步的。</li>
<li>异步逻辑都应该封装到 <strong>action</strong> 里面。</li>
</ol>
<p>只要你遵守以上规则，如何组织代码随你便。如果你的 store 文件太大，只需将 action、mutation 和 getter 分割到单独的文件。</p>
<p>对于大型应用，我们会希望把 Vuex 相关代码分割到模块中。下面是项目结构示例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">├── index.html</span><br><span class="line">├── main.js</span><br><span class="line">├── api</span><br><span class="line">│   └── ... <span class="comment"># 抽取出API请求</span></span><br><span class="line">├── components</span><br><span class="line">│   ├── App.vue</span><br><span class="line">│   └── ...</span><br><span class="line">└── store</span><br><span class="line">    ├── index.js          <span class="comment"># 我们组装模块并导出 store 的地方</span></span><br><span class="line">    ├── actions.js        <span class="comment"># 根级别的 action</span></span><br><span class="line">    ├── mutations.js      <span class="comment"># 根级别的 mutation</span></span><br><span class="line">    └── modules</span><br><span class="line">        ├── cart.js       <span class="comment"># 购物车模块</span></span><br><span class="line">        └── products.js   <span class="comment"># 产品模块</span></span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703115309.png" alt="image-20200703115307665"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20200703115331.png" alt="image-20200703115329913"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Kylin</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.codekylin.cn/6620.html">https://www.codekylin.cn/6620.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.codekylin.cn" target="_blank">Kylin</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Vue/">Vue</a><a class="post-meta__tags" href="/tags/Vuex/">Vuex</a></div><div class="post_share"><div class="social-share" data-image="https://qiniu.codekylin.cn/github/img/img/博客封面7.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://qiniu.codekylin.cn/img/20200807181442.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181442.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://qiniu.codekylin.cn/img/20200807181505.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181505.jpg" alt="支付寶"/></a><div class="post-qr-code-desc">支付寶</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/1252.html"><img class="prev-cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-76qvyy.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">axios详解</div></div></a></div><div class="next-post pull-right"><a href="/41275.html"><img class="next-cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4d5ezg.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Promise的使用</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/5277.html" title="Vue CLI脚手架详解"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面9.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-12</div><div class="title">Vue CLI脚手架详解</div></div></a></div><div><a href="/30649.html" title="Vue学习-1"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/code3.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-02</div><div class="title">Vue学习-1</div></div></a></div><div><a href="/30457.html" title="Vue学习-2"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/deepin-2.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-03</div><div class="title">Vue学习-2</div></div></a></div><div><a href="/46648.html" title="Vue学习-3"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面6.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-03</div><div class="title">Vue学习-3</div></div></a></div><div><a href="/46264.html" title="Vue学习-5"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-j5jyjp.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-13</div><div class="title">Vue学习-5</div></div></a></div><div><a href="/29817.html" title="Vue学习-4"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-nrxddq.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-05</div><div class="title">Vue学习-4</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="this.onerror=null;this.src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Kylin</div><div class="author-info__description">学习不易，努力努力~</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div><a class="button--animated" id="card-info-btn"><i class="fas fa-bookmark"></i><span>加入书签</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">学习不易，努力努力！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Vuex%E6%98%AF%E5%81%9A%E4%BB%80%E4%B9%88%E7%9A%84%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">Vuex是做什么的？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%A1%E7%90%86%E4%BB%80%E4%B9%88%E7%8A%B6%E6%80%81%E5%91%A2%EF%BC%9F"><span class="toc-number">2.</span> <span class="toc-text">管理什么状态呢？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8D%95%E7%95%8C%E9%9D%A2%E7%9A%84%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86"><span class="toc-number">3.</span> <span class="toc-text">单界面的状态管理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E7%95%8C%E9%9D%A2%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86"><span class="toc-number">4.</span> <span class="toc-text">多界面状态管理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vuex%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-number">5.</span> <span class="toc-text">Vuex的基本使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Vuex%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86%E5%9B%BE%E4%BE%8B"><span class="toc-number">6.</span> <span class="toc-text">Vuex状态管理图例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#State"><span class="toc-number">7.</span> <span class="toc-text">State</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Getters"><span class="toc-number">8.</span> <span class="toc-text">Getters</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mutations"><span class="toc-number">9.</span> <span class="toc-text">mutations</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%8A%B6%E6%80%81%E6%9B%B4%E6%96%B0"><span class="toc-number">9.1.</span> <span class="toc-text">状态更新</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%90%E4%BA%A4%E8%BD%BD%E8%8D%B7"><span class="toc-number">9.2.</span> <span class="toc-text">提交载荷</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E9%A3%8E%E6%A0%BC%E7%9A%84%E6%8F%90%E4%BA%A4%E6%96%B9%E5%BC%8F"><span class="toc-number">9.3.</span> <span class="toc-text">对象风格的提交方式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mutation-%E9%9C%80%E9%81%B5%E5%AE%88-Vue-%E7%9A%84%E5%93%8D%E5%BA%94%E8%A7%84%E5%88%99"><span class="toc-number">9.4.</span> <span class="toc-text">Mutation 需遵守 Vue 的响应规则</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%B8%B8%E9%87%8F%E6%9B%BF%E4%BB%A3-Mutation-%E4%BA%8B%E4%BB%B6%E7%B1%BB%E5%9E%8B"><span class="toc-number">9.5.</span> <span class="toc-text">使用常量替代 Mutation 事件类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mutation-%E5%BF%85%E9%A1%BB%E6%98%AF%E5%90%8C%E6%AD%A5%E5%87%BD%E6%95%B0"><span class="toc-number">9.6.</span> <span class="toc-text">Mutation 必须是同步函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Actions"><span class="toc-number">10.</span> <span class="toc-text">Actions</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Module"><span class="toc-number">11.</span> <span class="toc-text">Module</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-number">11.1.</span> <span class="toc-text">基本使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Module%E5%B1%80%E9%83%A8%E7%8A%B6%E6%80%81"><span class="toc-number">11.2.</span> <span class="toc-text">Module局部状态</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Actions%E7%9A%84%E5%86%99%E6%B3%95"><span class="toc-number">11.3.</span> <span class="toc-text">Actions的写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84"><span class="toc-number">12.</span> <span class="toc-text">项目结构</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/56352.html" title="be动词"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面10.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="be动词"/></a><div class="content"><a class="title" href="/56352.html" title="be动词">be动词</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/36436.html" title="JVM堆内存"><img data-lazy-src="https://qiniu.codekylin.cn/img/20200418115059.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM堆内存"/></a><div class="content"><a class="title" href="/36436.html" title="JVM堆内存">JVM堆内存</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/44292.html" title="Java多线程详解"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-eorjzk.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java多线程详解"/></a><div class="content"><a class="title" href="/44292.html" title="Java多线程详解">Java多线程详解</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/40200.html" title="谷粒商城记录"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-6qvvrx.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="谷粒商城记录"/></a><div class="content"><a class="title" href="/40200.html" title="谷粒商城记录">谷粒商城记录</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/27082.html" title="Spring学习-3"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4x28xo.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习-3"/></a><div class="content"><a class="title" href="/27082.html" title="Spring学习-3">Spring学习-3</a><time datetime="2022-07-12T11:47:29.799Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://qiniu.codekylin.cn/github/img/img/博客封面7.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By Kylin</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="https://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png"><span>湘ICP备2022005420号-1</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
      appKey: 'ATug9IScYQBHILhKWEqBHYxM',
      placeholder: '昵称填入QQ号能获取到QQ头像哦~请输入正确的邮箱地址，你将会快速收到我的回复并且通过邮件通知你！~',
      avatar: 'robohash',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-cn',
      recordIP: false,
      serverURLs: 'https://cliyiuhj.lc-cn-n1-shared.com',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script></div></body></html>